<?php

namespace common\models;

use backend\models\ProjectPreEvaluationValue;
use Yii;
use backend\models\ProjectPreEvaluationSeal;

/**
 * This is the model class for table "project_pre_evaluation_mortgage".
 *
 * @property integer $id
 * @property string $project_id
 * @property string $mortgagor
 * @property string $mortgage_principal
 * @property string $mortgage_interest
 * @property string $guarantor
 * @property string $created_at
 */
class ProjectPreEvaluationMortgage extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'project_pre_evaluation_mortgage';
    }
    /*关联表 抵押物列表（ly）*/
    public function getSeal(){
        return $this->hasMany(ProjectPreEvaluationSeal::className(),['mortgage_id'=>'id']);
    }
    /*关联表（ly） 抵押物列表 project_pre_evaluation_value*/
    public function getValue(){
        return $this->hasOne(ProjectPreEvaluationValue::className(),['mortgage_id'=>'id']);
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['project_id', 'mortgagor', 'mortgage_principal', 'mortgage_interest', 'guarantor'], 'required'],
            [['project_id'], 'integer'],
            [['created_at'], 'safe'],
            [['mortgagor', 'mortgage_principal', 'mortgage_interest', 'guarantor'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'project_id' => '项目',
            'mortgagor' => '抵押人',
            'mortgage_principal' => '抵押本金（万元）',
            'mortgage_interest' => '抵押利息（万元）',
            'guarantor' => '保证人',
            'created_at' => '添加时间',
        ];
    }

    /**
     * @param $id 主键
     * @param $project_id 项目id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 项目修改日志module
     * @param $module_type 项目类型 1混合类，2抵押类
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public static function setUpdateLog($id, $project_id, $changedAttributes, $userId, $module/*, $module_type*/, $type)
    {
        $model = self::findOne((int)$id);
        $project = Project::findOne($project_id);
        if ($model === null || $project === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        if ($project->type != 2 ) {
            $project->type = 1;
        }

        $attributeLabels = $model->attributeLabels();
        $intAttributeLabels = ['project_id', 'lock_user'];
        $userInfo = (new UserModel())->getDepartmentUsersList();

        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                /*case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;*/
                                default:
                            }
                        }
                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    //return array('state' => true, 'msg' => '添加预评估信息非抵押物情况修改记录成功');
                    return array('state' => true, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'project_id':
                                    $value = $project->title;
                                    break;
                                /*case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;*/
                                default;
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
            default:
        }

        try {
            $time = date('Y-m-d H:i:s');
            $projectUpdateLog = new ProjectUpdateLog();
            if ($project->type !=2 ) {
                $project->type = 1;
            }
            $module_title_array = $projectUpdateLog->getModuleArrayTitle($project->type);
            $projectUpdateLog->project_id = $project_id;
            $projectUpdateLog->module = $module_title_array[$module];
            $projectUpdateLog->type = $project->type;
            $projectUpdateLog->created_at = $time;
            $projectUpdateLog->user_id = $userId;
            $projectUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
            $re1 = $projectUpdateLog->save();
            if (!$re1) {
                throw new \Exception('预评估信息非抵押物情况记录添加失败');
            }

            return array('state' => true, 'msg' => '添加预评估信息非抵押物情况修改记录成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
